package Controllers;

import DB.DBCustomer;
import DB.DBLocation;
import Models.Customer;
import Models.Location;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class CustomerController implements ControllerInterface<Customer>
{
	public CustomerController ()
	{}

	public int insert(Customer customer)
	{
		DBCustomer dbc = new DBCustomer();
		int customerNo = dbc.insert(customer.exportData());
		
		customer.setCustomerNo(customerNo);
		customer.setCustomerNoOnLocations();
		insertDependent(customer.getLocations());

		return customerNo;
	}

	public void insertDependent(ArrayList<? extends DB.RowInterface> data)
	{
		DBLocation dbl = new DBLocation();
		ArrayList<HashMap> rowsData = new ArrayList<HashMap>();
		Iterator<Location> i = ((ArrayList<Location>)data).iterator();
		while(i.hasNext())
		{
			Location location = i.next();
			if(dbl.alreadyExists(location.getLocationNo()))
			{
				dbl.update(location.exportData(), "locationNo = "+location.getLocationNo());
			}
			else
			{
				rowsData.add(location.exportData());
			}
		}
		dbl.insert(rowsData);
	}

	public Customer find(int id)
	{
		DBCustomer dbc = new DBCustomer();
		return dbc.fetchByNo(id);
	}

	public int update(Customer customer, String where)
	{
		HashMap loData = new HashMap();

		loData.put("address", customer.getLocation().getAddress());
		loData.put("zipCode", customer.getLocation().getZipCode());

		DBLocation dbl = new DBLocation();
		int locationNo = customer.getLocation().getLocationNo();
		if(dbl.alreadyExists(locationNo))
		{
			dbl.update(loData, "locationNo = "+locationNo);
		}
		else
		{
			locationNo = dbl.insert(loData);
		}

		customer.setLocationNo(locationNo);
		HashMap cuData = customer.exportData();

		updateDependent(customer.getLocations(), null);

		DBCustomer dbc = new DBCustomer();
		return dbc.update(cuData, where);
	}

	public void updateDependent(ArrayList<? extends DB.RowInterface> data, String where)
	{
		DBLocation dbl = new DBLocation();
		Iterator<Location> i = ((ArrayList<Location>)data).iterator();
		while(i.hasNext())
		{
			Location location = i.next();
			if(dbl.alreadyExists(location.getLocationNo()))
			{
				dbl.update(location.exportData(), "locationNo = "+location.getLocationNo());
			}
			else
			{
				dbl.insert(location.exportData());
			}
		}
	}

	public int delete(int id)
	{
		DBCustomer dbc = new DBCustomer();
		return dbc.deleteByNo(id);
	}

	public ArrayList<Customer> fetchAll()
	{
		DBCustomer dbc = new DBCustomer();
		return dbc.fetchAll();
	}
}